package kr.co.bettersoft.pushchat.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import kr.co.bettersoft.pushchat.common.CommonConstant;
import kr.co.bettersoft.pushchat.common.CommonUtil;
import kr.co.bettersoft.pushchat.common.PushChatRest;
import kr.co.bettersoft.pushchat.domain.PushChatChat;
import kr.co.bettersoft.pushchat.domain.PushChatFriend;
import kr.co.bettersoft.pushchat.domain.PushChatMember;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsProfileActivity extends Activity{
	String TAG = "SettingsProfileActivity";

	public String COLOR_SELECTED = "#ff0000";
	public String COLOR_NOT_SELECTED = "#000000";


	public final int REQ_CODE_PICK_PICTURE = 601;				// 이미지 선택 코드. activity result 받기 위한 값

	public final int SELECT_MEMBER_INFORMATION = 602;				// 사용자 프로필 정보를 가져온다		RestSelectMemberInformation  멤버 상세정보
	//	public final int ss = 603;				// 닉네임 중복검사를 한다			// 기능 없음
	public final int UPDATE_MEMBER_INFORMATION = 604;				// 사용자 프로필 정보를 업데이트 한다		updateMemberInformation		updateMemberInformationWithProfileImage


	public final int MAX_WIDTH = CommonConstant.UPLOAD_IMAGE_SIZE_BIG;				// 업로드 이미지 큰변 길이 800
	public final int MAX_HEIGHT = CommonConstant.UPLOAD_IMAGE_SIZE_SMALL;			// 업로드 이미지 작은변 길이 600


	// qr
	String userId;		// 사용자 아이디
	// 설정 파일 저장소  - 사용자 전번 읽기 / 쓰기 용도	
	SharedPreferences sharedPrefCustom;
	// 중복 실행 방지용
	int isUpdating = 0;
	/////////////////////////////////////////////////////////////////////////////

	Button topNaviCloseBtn; 		// 상단 닫기 버튼

	View parent_layout;				// 최상위 - 키보드 숨김용
	View title_layout;				//  키보드 숨김용
	View profile_master_view;		// 전체 - > 한번에 보여주기 위함

	TextView profile_member_id_txt;		// 멤버 아이디

	Button select_img_btn;				// 이미지 선택 버튼
	Button delete_img_btn;				// 이미지 삭제 버튼
	ImageView select_img_thumb_view;	// 이미지 썸네일 뷰

	EditText profile_nick_name_edit_txt;		// 닉네임		
	Button profile_nick_duplication_check_btn;	// 닉 중복체크 버튼
	EditText profile_comment_edit_txt;			// 커멘트

	Button profile_gender_na_btn;			// 성별 N/A
	Button profile_gender_male_btn;			// 성별 남
	Button profile_gender_female_btn;		// 성별 여
	Button profile_gender_etc_btn;			// 성별 기타

	Button profile_age_na_btn;			// 나이 N/A
	Button profile_age_10_btn;			// 나이 10
	Button profile_age_20_btn;			// 나이 20
	Button profile_age_30_btn;			// 나이 30
	Button profile_age_40_btn;			// 나이 40
	Button profile_age_50_btn;			// 나이 50
	Button profile_age_60_btn;			// 나이 60

	EditText profile_email_edit_txt;	// 이메일

	TextView profile_register_date_txt;	// 등록일

	Button profile_save_btn;			// 저장 버튼


	// 진행바
	ProgressBar pb1;		// 중단 로딩 진행바

	// 키보드 자동 숨기기 위한 부모 레이아웃(리스너 달아서 키보드 숨김)과 입력 매니저
	View parentLayout;		
	InputMethodManager imm;

	// 서버 통신
	String certiResult="";
	PushChatRest pushChatRest;
	String callResult = "";
	String tempstr = "";
	JSONObject jsonObject;

	PushChatMember pushChatMemberServer;	// 멤버 정보

	//	Boolean isMyFriend = false;			// 친구 등록 여부

	String selectedGender = "N/A";		// 선택된 성별
	String selectedAge = "N/A";		// 선택된 나이
	// 선택한 이미지
	public static Bitmap selectedImg = null;

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		// 받아온결과를 화면에 뿌려준다.
				if(b.getInt("showYN")==1){
					// merchantData 에서 데이터 꺼내어 화면에 세팅한다.			// titleImg , name , companyName , phone , addr , pr ,,
					hidePb();

					profile_member_id_txt.setText(pushChatMemberServer.getMemberId());
					if(pushChatMemberServer.getRegisterDate()!=null&&pushChatMemberServer.getRegisterDate().length()>0){
						profile_register_date_txt.setText(getString(R.string.reg_date)+pushChatMemberServer.getRegisterDate());
					}

					selectedGender = pushChatMemberServer.getGender();
					selectedAge = pushChatMemberServer.getAge();

					if(selectedGender.equals("MALE")){
						profile_gender_male_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedGender.equals("FEMALE")){
						profile_gender_female_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedGender.equals("ETC")){
						profile_gender_etc_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else{
						profile_gender_na_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}
					if(selectedAge.equals("10")){
						profile_age_10_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedAge.equals("20")){
						profile_age_20_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedAge.equals("30")){
						profile_age_30_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedAge.equals("40")){
						profile_age_40_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedAge.equals("50")){
						profile_age_50_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else if(selectedAge.equals("60")){
						profile_age_60_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}else{
						profile_age_na_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
					}

					profile_nick_name_edit_txt.setText(pushChatMemberServer.getNickName());
					profile_comment_edit_txt.setText(pushChatMemberServer.getComment());
					profile_email_edit_txt.setText(pushChatMemberServer.getEmail());

					if(pushChatMemberServer.getProfileImage()!=null){
						//  이미지 가져와서 붙임
						select_img_thumb_view.setImageBitmap(pushChatMemberServer.getProfileImage());
					}else{
						select_img_thumb_view.setImageDrawable(getResources().getDrawable(R.drawable.sub7_4));
					}
					profile_master_view.setVisibility(View.VISIBLE);
				}
				if(b.getInt("showAlert")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 그냥 사용자 확인 용이기 때문에 추가 조작 없음.
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("showAlertAndFinish")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_dialog_img)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}})
						.setNegativeButton("", null).show();
				}
				if(b.getInt("order")==1){ 		// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){ // 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}
				if(b.getInt("showErrToast")==1){
					Toast.makeText(SettingsProfileActivity.this, R.string.error_message, Toast.LENGTH_SHORT).show();
				}

				switch (msg.what)
				{
				//					// 멤버 상세 정보 가져오기
				case SELECT_MEMBER_INFORMATION   : runOnUiThread(new RunnableSelectMemberInformation());			
				break;
				//					// 사용자 프로필 정보를 업데이트 한다		 		
				case UPDATE_MEMBER_INFORMATION   : runOnUiThread(new RunnableUpdateMemberInformation());			
				break;
				default : 
					break;
				}	
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	//////////////////////////////////////////////////////////////////////////////////////////////////////////


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );		// no title
		setContentView(R.layout.settings_profile_activity);

		pushChatRest = new PushChatRest();

		parent_layout = (View)findViewById(R.id.parent_layout);					// 최상위 뷰
		title_layout = (View)findViewById(R.id.title_layout);					// 
		parent_layout = (View)findViewById(R.id.parent_layout);					// 

		profile_master_view = (View)findViewById(R.id.profile_master_view);		// 마스터 뷰

		select_img_thumb_view = (ImageView)findViewById(R.id.select_img_thumb_view);

		profile_member_id_txt = (TextView)findViewById(R.id.profile_member_id_txt);
		profile_register_date_txt = (TextView)findViewById(R.id.profile_register_date_txt);

		profile_nick_name_edit_txt = (EditText)findViewById(R.id.profile_nick_name_edit_txt);
		profile_comment_edit_txt = (EditText)findViewById(R.id.profile_comment_edit_txt);
		profile_email_edit_txt = (EditText)findViewById(R.id.profile_email_edit_txt);


		parent_layout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);
			}
		});
		title_layout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);
			}
		});
		profile_master_view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);
			}
		});

		profile_comment_edit_txt.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// 엔터 입력시 3줄까지만 작동. - 주석처리
				if(keyCode==KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_DOWN){
					Log.d(TAG,"KEYCODE_ENTER");
					if(profile_comment_edit_txt.getLineCount()>2){
						//						return true;
					}
				}

				return false;
			}
		});

		select_img_btn = (Button) findViewById(R.id.select_img_btn);
		delete_img_btn = (Button) findViewById(R.id.delete_img_btn);
		profile_nick_duplication_check_btn = (Button) findViewById(R.id.profile_nick_duplication_check_btn);
		profile_gender_na_btn = (Button) findViewById(R.id.profile_gender_na_btn);
		profile_gender_male_btn = (Button) findViewById(R.id.profile_gender_male_btn);
		profile_gender_female_btn = (Button) findViewById(R.id.profile_gender_female_btn);
		profile_gender_etc_btn = (Button) findViewById(R.id.profile_gender_etc_btn);
		profile_age_na_btn = (Button) findViewById(R.id.profile_age_na_btn);
		profile_age_10_btn = (Button) findViewById(R.id.profile_age_10_btn);
		profile_age_20_btn = (Button) findViewById(R.id.profile_age_20_btn);
		profile_age_30_btn = (Button) findViewById(R.id.profile_age_30_btn);
		profile_age_40_btn = (Button) findViewById(R.id.profile_age_40_btn);
		profile_age_50_btn = (Button) findViewById(R.id.profile_age_50_btn);
		profile_age_60_btn = (Button) findViewById(R.id.profile_age_60_btn);
		profile_save_btn = (Button) findViewById(R.id.profile_save_btn);

		topNaviCloseBtn = (Button) findViewById(R.id.top_navi_close_btn);
		// 상단 닫기 버튼
		topNaviCloseBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d(TAG,"topNaviCloseBtn clicked");
				finish();
			}
		});

		// progress bar
		pb1 = (ProgressBar) findViewById(R.id.member_info_pb);		// 로딩(중앙)

		//		showPb();

		// prefs
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,				
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		userId = sharedPrefCustom.getString("userId", "");	
		//		if(userId.length()<1){
		//			Log.d(TAG,"no saved userId");
		//			finish();
		//		}

		if(isUpdating==0){
			handler.sendEmptyMessage(SELECT_MEMBER_INFORMATION);
			//			handler.sendEmptyMessage(REST_SELECT_DUPLICATION_FRIEND);	// 친구 여부부터 확인하고 친구 정보 가져오도록 한다
			////			handler.sendEmptyMessage(REST_SELECT_MEMBER_INFORMATION);

		}
	}

	/**
	 * 버튼 리스너
	 */
	public void profileOnClickListener(View v) {
		//		Log.d(TAG,"profileOnClickListener");
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);

		switch(v.getId()) {
		case R.id.select_img_btn:
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);
			Intent imgSelectIntent = new Intent(Intent.ACTION_PICK);
			imgSelectIntent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
			imgSelectIntent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);	// images on the SD card
			// 결과를 리턴하는 activity 호출
			startActivityForResult(imgSelectIntent, REQ_CODE_PICK_PICTURE);	
			break;
		case R.id.delete_img_btn:
			imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm .hideSoftInputFromWindow(profile_email_edit_txt.getWindowToken(), 0);
			//			Uri curImgURI = data.getData();
			try {
				////				selectedImg = Images.Media.getBitmap(getContentResolver(), curImgURI );
				//				Drawable drawableNoImg = getResources().getDrawable(R.drawable.sub7_4);
				//				BitmapDrawable bmpDrawableNoImg = (BitmapDrawable) drawableNoImg;
				//				selectedImg = bmpDrawableNoImg.getBitmap(); 
				// 섬네일 초기화
				//				select_img_thumb_view.setImageBitmap(selectedImg);
				select_img_thumb_view.setImageDrawable(getResources().getDrawable(R.drawable.sub7_4));
				selectedImg = null;
			} catch (Exception e) { e.printStackTrace(); }
			break;

		case R.id.profile_nick_duplication_check_btn:
			break;

		case R.id.profile_gender_na_btn:
			selectedGender = (String) v.getTag();
			profile_gender_na_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_gender_male_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_female_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_etc_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_gender_male_btn:
			profile_gender_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_male_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_gender_female_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_etc_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			selectedGender = (String) v.getTag();
			break;
		case R.id.profile_gender_female_btn:
			profile_gender_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_male_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_female_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_gender_etc_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			selectedGender = (String) v.getTag();
			break;
		case R.id.profile_gender_etc_btn:
			profile_gender_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_male_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_female_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_gender_etc_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			selectedGender = (String) v.getTag();
			break;

		case R.id.profile_age_na_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_10_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_20_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_30_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_40_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_50_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			break;
		case R.id.profile_age_60_btn:
			selectedAge = (String) v.getTag();
			profile_age_na_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_10_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_20_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_30_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_40_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_50_btn.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
			profile_age_60_btn.setTextColor(Color.parseColor(COLOR_SELECTED));
			break;
		case R.id.profile_save_btn:
			handler.sendEmptyMessage(UPDATE_MEMBER_INFORMATION);
			break;
		}
	}




	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////////////////////
	// 비동기 통신.

	/**
	 * 러너블. 멤버 상세 정보를 가져온다.
	 */
	class RunnableSelectMemberInformation implements Runnable {
		public void run(){
			new backgroundSelectMemberInformation().execute();
		}
	}
	/**
	 * 비동기로 멤버 상세 정보를 가져온다.
	 * backgroundSelectMemberInformation
	 */
	public class backgroundSelectMemberInformation extends  AsyncTask<Void, Void, Void> { 
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundSelectMemberInformation");

			if(isUpdating==0){
				isUpdating = 1;
				// 파리미터 세팅
				PushChatMember pushChatMemberParam = new PushChatMember();
				pushChatMemberParam.setMemberId(userId);
				// 호출
				showPb();
				callResult = pushChatRest.RestSelectMemberInformation(pushChatMemberParam, returnThis());		
				// 결과 처리
				if(!(callResult.equals("F"))){		
					//					pushChatMemberServer = pushChatRest.getPushChatMember();
					CommonUtil commonUtil = new CommonUtil();
					Date tempDate = new Date();
					try {
						jsonObject = new JSONObject(callResult);		// member
						PushChatMember pushChatMember = new PushChatMember();
						pushChatMember.setMemberId(jsonObject.getString("memberId"));
						if(pushChatMember.getMemberId()==null || pushChatMember.getMemberId().length()<1){
							pushChatMember.setMemberId("");
							callResult = "F";
						}
						pushChatMember.setNickName(jsonObject.getString("nickName"));
						if(pushChatMember.getNickName()==null || pushChatMember.getNickName().length()<1){
							pushChatMember.setNickName("");
						}
						pushChatMember.setComment(jsonObject.getString("comment"));
						if(pushChatMember.getComment()==null || pushChatMember.getComment().length()<1){
							pushChatMember.setComment("");
						}
						pushChatMember.setProfileImageUrl(jsonObject.getString("profileImageUrl"));
						if(pushChatMember.getProfileImageUrl()==null || pushChatMember.getProfileImageUrl().length()<1){
							pushChatMember.setProfileImageUrl("");
						}else{
							//  이미지 가져와서 붙임
							try{
								Bitmap bmp = LoadImage(pushChatMember.getProfileImageUrl());
								pushChatMember.setProfileImage(bmp);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
						pushChatMember.setGender(jsonObject.getString("gender"));
						if(pushChatMember.getGender()==null || pushChatMember.getGender().length()<1){
							pushChatMember.setGender("");
						}
						pushChatMember.setEmail(jsonObject.getString("email"));
						if(pushChatMember.getEmail()==null || pushChatMember.getEmail().length()<1){
							pushChatMember.setEmail("");
						}
						pushChatMember.setAge(jsonObject.getString("age"));
						if(pushChatMember.getAge()==null || pushChatMember.getAge().length()<1){
							pushChatMember.setAge("");
						}
						//					pushChatMember.setRegisterDate(jsonObject.getString("registerDate"));
						String tempRegisterDate = jsonObject.getString("registerDate");
						// 형변환 작업
						tempDate = commonUtil.sf.parse(tempRegisterDate);
						//							commonUtil.context = context;

						String year = getString(R.string.year);
						String month = getString(R.string.month);
						String day = getString(R.string.day);
						String hour = getString(R.string.hour);
						String minute = getString(R.string.minute);
						SimpleDateFormat sfGeneral = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);
						SimpleDateFormat sfGeneral2 = new SimpleDateFormat("yyyy"+year+" MM"+month+" dd"+day+" HH"+hour+" mm"+minute);
						SimpleDateFormat sfGeneralChat = new SimpleDateFormat("MM"+month+" dd"+day+" a hh"+hour+" mm"+minute);

						tempRegisterDate = sfGeneral.format(tempDate);
						pushChatMember.setRegisterDate(tempRegisterDate);
						if(pushChatMember.getRegisterDate()==null || pushChatMember.getRegisterDate().length()<1){
							pushChatMember.setRegisterDate("");
						}
						pushChatMember.setPhoneNumber(jsonObject.getString("phoneNumber"));
						if(pushChatMember.getPhoneNumber()==null || pushChatMember.getPhoneNumber().length()<1){
							pushChatMember.setPhoneNumber("");
						}
						pushChatMember.setCountryCode(jsonObject.getString("countryCode"));
						if(pushChatMember.getCountryCode()==null || pushChatMember.getCountryCode().length()<1){
							pushChatMember.setCountryCode("");
						}
						pushChatMember.setLanguageCode(jsonObject.getString("languageCode"));
						if(pushChatMember.getLanguageCode()==null || pushChatMember.getLanguageCode().length()<1){
							pushChatMember.setLanguageCode("");
						}
						pushChatMember.setLatitude(jsonObject.getString("latitude"));
						if(pushChatMember.getLatitude()==null || pushChatMember.getLatitude().length()<1){
							pushChatMember.setLatitude("");
						}
						pushChatMember.setLongitude(jsonObject.getString("longitude"));
						if(pushChatMember.getLongitude()==null || pushChatMember.getLongitude().length()<1){
							pushChatMember.setLongitude("");
						}
						pushChatMember.setLocation(jsonObject.getString("location"));
						if(pushChatMember.getLocation()==null || pushChatMember.getLocation().length()<1){
							pushChatMember.setLocation("");
						}
						pushChatMember.setOpenLocationYn(jsonObject.getString("openLocationYn"));
						if(pushChatMember.getOpenLocationYn()==null || pushChatMember.getOpenLocationYn().length()<1){
							pushChatMember.setOpenLocationYn("");
						}
						pushChatMember.setPersonalityType(jsonObject.getString("personalityType"));
						if(pushChatMember.getPersonalityType()==null || pushChatMember.getPersonalityType().length()<1){
							pushChatMember.setPersonalityType("");
						}
						pushChatMember.setDeviceType(jsonObject.getString("deviceType"));
						if(pushChatMember.getDeviceType()==null || pushChatMember.getDeviceType().length()<1){
							pushChatMember.setDeviceType("");
						}
						pushChatMember.setRegistrationId(jsonObject.getString("registrationId"));
						if(pushChatMember.getRegistrationId()==null || pushChatMember.getRegistrationId().length()<1){
							pushChatMember.setRegistrationId("");
						}
						pushChatMember.setReceiveNotificationYn(jsonObject.getString("receiveNotificationYn"));
						if(pushChatMember.getReceiveNotificationYn()==null || pushChatMember.getReceiveNotificationYn().length()<1){
							pushChatMember.setReceiveNotificationYn("");
						}

						pushChatMemberServer = pushChatMember;
						showInfo();
					} catch (Exception e) {
						//						callResult = "F";
						showMSG();
					}
				}else{														 
					showMSG();
				}
				hidePb();
				isUpdating = 0;
			}else{
				Log.d(TAG,"already updating..");
			}
			return null; 
		}
	}

	/**
	 * 러너블. 사용자 프로필 정보를 업데이트 한다		
	 */
	class RunnableUpdateMemberInformation implements Runnable {
		public void run(){
			new backgroundUpdateMemberInformation().execute();
		}
	}
	/**
	 * 비동기로 사용자 프로필 정보를 업데이트 한다
	 * backgroundUpdateMemberInformation
	 */
	public class backgroundUpdateMemberInformation extends  AsyncTask<Void, Void, Void> { 
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundUpdateMemberInformation");

			if(isUpdating==0){
				isUpdating = 1;
				// 파리미터 세팅
				PushChatMember pushChatMemberParam = new PushChatMember();
				pushChatMemberParam.setMemberId(userId);
				pushChatMemberParam.setNickName(profile_nick_name_edit_txt.getText()+"");
				pushChatMemberParam.setEmail(profile_email_edit_txt.getText()+"");
				pushChatMemberParam.setComment(profile_comment_edit_txt.getText()+"");
				if(selectedImg==null){
					pushChatMemberParam.setProfileImageUrl(pushChatMemberServer.getProfileImageUrl());
					pushChatMemberParam.setThumbnailUrl(pushChatMemberServer.getThumbnailUrl());
				}else{
					pushChatMemberParam.setProfileImageUrl("");
					pushChatMemberParam.setThumbnailUrl("");
				}
				pushChatMemberParam.setGender(selectedGender);
				pushChatMemberParam.setAge(selectedAge);
				pushChatMemberParam.setPhoneNumber(pushChatMemberServer.getPhoneNumber());
				pushChatMemberParam.setCountryCode(pushChatMemberServer.getCountryCode());
				pushChatMemberParam.setLanguageCode(pushChatMemberServer.getLanguageCode());
				pushChatMemberParam.setLatitude(pushChatMemberServer.getLatitude());
				pushChatMemberParam.setLongitude(pushChatMemberServer.getLongitude());
				pushChatMemberParam.setLocation(pushChatMemberServer.getLocation());
				pushChatMemberParam.setOpenLocationYn(pushChatMemberServer.getOpenLocationYn());
				pushChatMemberParam.setPersonalityType(pushChatMemberServer.getPersonalityType());
				pushChatMemberParam.setDeviceType(pushChatMemberServer.getDeviceType());
				pushChatMemberParam.setRegistrationId(pushChatMemberServer.getRegistrationId());
				pushChatMemberParam.setReceiveNotificationYn(pushChatMemberServer.getReceiveNotificationYn());

				/*
				 * pushChatMemberServer
				 * 			
//				 * {"memberId":"test01",
//				 * "password":"7110eda4d09e062aa5e4a390b0a572ac0d2c0220",
//				 * "nickName":"최대일",
				 * "phoneNumber":"01022173645",
				 * "email":"",
				 * "comment":"돈까스가 세계최고!",
				 * "profileImageUrl":"",
				 * "thumbnailUrl":"",
				 * "gender":"",
				 * "age":"",
				 * "countryCode":"",
				 * "languageCode":"",
				 * "latitude":"","longitude":"",
				 * "location":"",
				 * "openLocationYn":"",
				 * "personalityType":"",
				 * "deviceType":"AS",
				 * "registrationId":"APA91bG6EBKJK-iDzsHGWwTclcXJYAakczBaFQ3uDEOQLoZ0wR3c8CdmmI_SirTs_n1nOtEZGu1F7f8_UmnJZbkXK8XzrMxWBG7dMNKBSnV0qqtPOxCloNkJsDUgHm6lG2XJgpbmFdEF5NcgYrDVntLoN11NQJ-yokDxJ3frDwrWBCxoNkAwVGo",
				 * "receiveNotificationYn":"Y",
				 * "restrictionYn":null,
				 * "activateYn":"Y",
				 * "modifyDate":"2013-10-22 11:55:42",
				 * "registerDate":"2013-06-14 14:33:47",
				 */
				// 호출
				showPb();
				if(selectedImg==null){
					callResult = pushChatRest.RestUpdateMemberInformation(pushChatMemberParam);	
				}else{
					Log.d(TAG,"img size:"+selectedImg.getWidth()+"x"+selectedImg.getHeight());
					selectedImg = resizeBitmapImage(selectedImg, MAX_WIDTH, MAX_HEIGHT);	 		// resize
					Log.d(TAG,"img size2:"+selectedImg.getWidth()+"x"+selectedImg.getHeight());				
					//					imageFileParam.setFileName(fineName);		// 이름은 나중에 rest에서 설정함


					pushChatMemberParam.setProfileImage(selectedImg);
					callResult = pushChatRest.RestUpdateMemberInformationWithProfileImage(pushChatMemberParam, returnThis());	
				}
				// 결과 처리
				if(callResult.equals("SUCCESS")){	
					showAlertAndFinish(getString(R.string.save_success));
				}else{	// 성공		
					showMSG();
				}
				hidePb();
				isUpdating = 0;
			}else{
				Log.d(TAG,"already updating..");
			}
			return null; 
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 * 이미지 선택 결과를 받아 처리한다.
	 */
	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode == REQ_CODE_PICK_PICTURE){
			if(resultCode==Activity.RESULT_OK){
				//					selectImgThumbView.setImageURI(data.getData());	// 선택한 사진 URI 로 연결하기
				// uri 에서 이미지 가져오기
				Uri curImgURI = data.getData();
				try {
					selectedImg = Images.Media.getBitmap(getContentResolver(), curImgURI );
				} catch (Exception e) { e.printStackTrace(); }
				// 섬네일 적용
				select_img_thumb_view.setImageBitmap(selectedImg);
			}
		}
	}



	/////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 가맹점 이미지 URL 에서 이미지 받아와서 도메인에 저장하는 부분.
	/**
	 * LoadImage
	 *  이미지 URL 에서 이미지 받아온 스트림을 비트맵으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return bm
	 */
	private Bitmap LoadImage( String $imagePath ) {
		InputStream inputStream = OpenHttpConnection( $imagePath ) ;
		Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;
		return bm;
	}
	/**
	 * OpenHttpConnection
	 *  이미지 URL 에서 이미지 받아와서 스트림으로 저장한다
	 *
	 * @param $imagePath
	 * @param
	 * @return stream
	 */
	private InputStream OpenHttpConnection(String $imagePath) {
		// TODO Auto-generated method stub
		InputStream stream = null ;
		try {
			URL url = new URL( $imagePath ) ;
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
			urlConnection.setRequestMethod( "GET" ) ;
			urlConnection.connect() ;
			if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {
				stream = urlConnection.getInputStream() ;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"MalformedURLException");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w(TAG,"IOException");
		}
		return stream ;
	}


	/**
	 * Bitmap이미지의 가로, 세로 사이즈를 리사이징 한다.
	 * 
	 * @param source 원본 Bitmap 객체
	 * @param maxResolution 제한 해상도
	 * @return 리사이즈된 이미지 Bitmap 객체
	 */
	public Bitmap resizeBitmapImage(Bitmap source, int maxWidth, int maxHeight)	{	// maxWidth 800 maxHeight 600
	
		int width = source.getWidth();
		int height = source.getHeight();

		Bitmap resizedBitmapImage;

		if(width > height){		// 너비가 더 크면 800 * 600
		
			resizedBitmapImage = Bitmap.createScaledBitmap(source, maxWidth, maxHeight, true);
		}else{// 높이가 더 크면 600 * 800
							
		
			resizedBitmapImage = Bitmap.createScaledBitmap(source, maxHeight, maxWidth, true);
		}
		return resizedBitmapImage;
	}

	/*
	 * Bitmap 이미지 리사이즈 -- xml 자체 설정으로 대체
	 * Src : 원본 Bitmap
	 * newHeight : 새로운 높이
	 * newWidth : 새로운 넓이
	 * 참고 소스 : http://skyswim42.egloos.com/3477279 ( webview 에서 capture 화면 resizing 하는 source 도 있음 )
	 */
	private BitmapDrawable BitmapResizePrc(Bitmap Src, float newHeight, float newWidth)
	{
		BitmapDrawable Result = null;
		int width = Src.getWidth();
		int height = Src.getHeight();

		// calculate the scale - in this case = 0.4f
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// createa matrix for the manipulation
		Matrix matrix = new Matrix();

		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);

		// rotate the Bitmap 회전 시키려면 주석 해제!
		//matrix.postRotate(45);

		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(Src, 0, 0, width, height, matrix, true);

		// check
		width = resizedBitmap.getWidth();
		height = resizedBitmap.getHeight();
		//		Log.i("ImageResize", "Image Resize Result : " + Boolean.toString((newHeight==height)&&(newWidth==width)) );

		// make a Drawable from Bitmap to allow to set the BitMap
		// to the ImageView, ImageButton or what ever
		Result = new BitmapDrawable(resizedBitmap);
		return Result;
	}


	///////////////////////////////////////////////////////////////////////////////////////////////////
	// 유틸

	/**
	 * returnThis
	 *  컨택스트를 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context returnThis(){
		return this;
	}
	/**
	 * showMSG
	 *  화면에 error 토스트 띄운다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showMSG(){			// 화면에 error 토스트 띄움..
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("showErrToast", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 

	/**
	 * showAlert
	 * 얼럿창을 띄운다
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlert(final String msg){
		SettingsProfileActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlert", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	/**
	 * showAlertAndFinish
	 * 얼럿창을 띄운다
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void showAlertAndFinish(final String msg){
		SettingsProfileActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlertAndFinish", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}

	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	// 화면에 보여준다..
	/**
	 * showInfo
	 *  받아온 정보를 화면에 보여준다.
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showInfo(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();
						Bundle b = new Bundle();
						b.putInt("showYN", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////
}